package com.hankol.material.fragment

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseLazyFragment
import com.baselibrary.bean.download.DownloadInfo
import com.baselibrary.db.DBManager
import com.baselibrary.utils.DoubleClickHelper
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.ToastUtils
import com.hankol.material.R
import com.hankol.material.adapter.TabDownloadingAdapter
import com.hankol.material.databinding.FragmentDownloadIngBinding
import com.hankol.material.help.PopUtils
import com.hankol.material.limit.DownloadLimitManager
import com.hankol.material.viewmodel.MaterialBaseViewModel
import com.hankol.material.viewmodel.TabDownloadingViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**Tab--下载中列表
 * @author: merbng
 * @time: 2021/10/15 10:36
 * @description:
 */
class DownloadingFragment : BaseLazyFragment(true) {

    lateinit var binding: FragmentDownloadIngBinding
    private var viewModel: TabDownloadingViewModel? = null
    val mAdapter: TabDownloadingAdapter by lazy { TabDownloadingAdapter() }
    private var hasnext: Boolean = false
    val timer = Timer();

    companion object {
        fun newInstance(): DownloadingFragment {
            return DownloadingFragment()
        }
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getFragmentViewModelProvider(this).get(TabDownloadingViewModel::class.java)
        binding.rvOrder.setLayoutManager(LinearLayoutManager(activity))
        binding.rvOrder.setAdapter(mAdapter)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.img_del -> {
                    if (DoubleClickHelper.isOnDoubleClick()) return@setOnItemChildClickListener
                    PopUtils.showRightLeftDialog(attachActivity, "确认删除下载信息", object : MaterialBaseViewModel.IRightLeftCallBack {
                        override fun leftClick() {

                        }

                        override fun rightClick() {
                            if (mAdapter.data.size == 0) return
                            DBManager.getInstance().deleteDownload(viewModel?.userIds!!, (mAdapter.data.get(position) as DownloadInfo).url)
                            DownloadLimitManager.getInstance().cancelDownload(mAdapter.data.get(position) as DownloadInfo)
                            mAdapter.data.remove(mAdapter.data.get(position) as DownloadInfo)
                            mAdapter.notifyDataSetChanged()
                            EventBusUtils.sendNotify(MessageBus.msgId_del_material_file)
                            ToastUtils.showShort(attachActivity, "文件已删除")
                            showEmpty(mAdapter.data.size)
                        }
                    })

                }
            }
        }
//        binding.sv.setHeader(SpringViewNewHeader(activity))
//        binding.sv.setFooter(SpringViewNewFooter(activity))
//        binding.sv.setType(SpringView.Type.FOLLOW)
//        binding.sv.setListener(object : SpringView.OnFreshListener {
//            override fun onRefresh() {
//                loadData()
//            }
//
//            override fun onLoadmore() {
//                if (hasnext) {
//                    loadData()
//                } else {
//                    binding.sv.onFinishFreshAndLoad()
//                }
//            }
//        })
        viewModel?.dataListLD?.observe(this, Observer {
            if (it != null) {
                mAdapter.setNewData(it)
                showEmpty(it.size)
            } else {
                showEmpty(0)
            }
            binding.tvEmpty.visibility = if (it != null && it.size > 0) View.GONE else View.VISIBLE
//            binding.sv.onFinishFreshAndLoad()
        })
        //5秒更新数据库 下载进度
        timer.scheduleAtFixedRate(object : TimerTask() {
            override fun run() {
                updateDownloadProgress()
            }
        }, 1000, 5000)
    }

    private fun updateDownloadProgress() {
        if (mAdapter.data.size == 0) {
            timer.cancel()
            return
        }
        for (i in mAdapter.data.indices) {
            DBManager.getInstance().updateDownload(mAdapter.data[i])
        }
    }

    private fun showEmpty(size: Int) {
        binding.tvEmpty.visibility = if (size > 0) View.GONE else View.VISIBLE
    }

    override fun lazyLoadData() {

    }

    fun loadData() {
        mAdapter.data.clear()
        viewModel?.getDownloadList()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_download_ing
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        if (timer != null) {
            timer.cancel()
        }
        super.onDestroy()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(info: DownloadInfo) {
        if (DownloadInfo.DOWNLOAD.equals(info.getDownloadStatus())) {
            mAdapter.updateProgress(info)
        } else if (DownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())) {
            val it = mAdapter.data.iterator()
            while (it.hasNext()) {
                val x = it.next()
                if (info.url.equals(x.url)) {
                    it.remove()
                    mAdapter.notifyDataSetChanged()
                    EventBusUtils.sendNotify(MessageBus.msgId_download_complete)

                    showEmpty(mAdapter.data.size)
                }
            }
            mAdapter.updateProgress(info)
        } else if (DownloadInfo.DOWNLOAD_PAUSE.equals(info.getDownloadStatus())) {
//            ToastUtils.showShort(attachActivity, "下载暂停")
        } else if (DownloadInfo.DOWNLOAD_ERROR.equals(info.getDownloadStatus())) {
            ToastUtils.showShort(attachActivity, "下载出错")
        }
    }

    override fun onResume() {
        super.onResume()
        loadData()
    }
}